﻿using CKS.Core.Framework;
using CKS.PLC.Action.System;
using FreeSql;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP40
{
    public class DB3041_CncB_UploadAction : SaveProcessingResults
    {
        /// <summary>
        /// CNC：B面，加工状态变化上传
        /// </summary>
        /// <param name="_value"></param>
        public DB3041_CncB_UploadAction(DecodeValue _value) : base(_value)
        {
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {

            string productCode = Value.GetLocationData(e.LocationId, 1).ToString();
            var record = new CksProductionRecord()
            {
                ProductCode = productCode,
                BSideMachineNumber = Value.GetLocationData(e.LocationId, 2).ToInt(),
                BSideToolingNumber = Value.GetLocationData(e.LocationId, 3).ToInt(),
                UploadStatus = Value.GetLocationData(e.LocationId, 4).ToInt()
            };
            ProcessData(record);
            return base.AfterSaved(e);


        }

        private void ProcessData(CksProductionRecord data)
        {
            if (data.ProductCode.IsEmpty())
                return;
            var res = SplitSuffixGrade(data.ProductCode);
            data.ProductCode = res.Code;
            var record = GetRecordByProductCode(data.ProductCode);
            record.ProductCode = data.ProductCode;
            record.BSideMachineNumber = data.BSideMachineNumber;
            record.BSideToolingNumber = data.BSideToolingNumber;

            string tag = "";
            switch (data.UploadStatus)
            {
                case 1:
                    record.ProcessingStatus = 9;
                    record.BSideLoadingTime = DateTime.Now;
                    tag = "投入";
                    break;
                case 2:
                    record.ProcessingStatus = 10;
                    record.BSideStartTime = DateTime.Now;
                    tag = "开始";
                    break;
                case 3:
                    record.ProcessingStatus = 11;
                    record.BSideEndTime = DateTime.Now;
                    tag = "结束";
                    break;
                case 4:
                    record.ProcessingStatus = 12;
                    record.BSideUnloadingTime = DateTime.Now;
                    tag = "取出";
                    break;
                default:
                    EventBus.AddLog($"CNC_B面 {record.ProductCode} 上传状态未知 {data.UploadStatus}");
                    return;
            }



            if (record.Id > 0)
                conn.Update<CksProductionRecord>()
                    .SetSource(record)
                    .UpdateColumns(a => new {
                        a.ProcessingStatus,
                        a.BSideMachineNumber,
                        a.BSideToolingNumber,
                        a.BSideLoadingTime,
                        a.BSideStartTime,
                        a.BSideEndTime,
                        a.BSideUnloadingTime
                    }).ExecuteAffrows();
            else
            {
                // 格式示例 PW 250624 0001  
                string dayCacheKey = $"PW{DateTime.Now.ToString("yyMMdd")}";
                var nextSeriaNumber = GetNextSerialNumber(dayCacheKey);
                record.SerialNumber = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";
                conn.Insert(record).ExecuteAffrows();
                conn.Update<CksKeyCache>()
                    .Set(a => a.MaxSerialNumber, nextSeriaNumber)
                   .Where(a => a.CacheKey == dayCacheKey).ExecuteAffrows();

            }
            EventBus.AddLog($"CNC_B面{tag}；工站：OP40;{record.CoverCode} 保存完成  ");

        }

        private CksProductionRecord GetRecordByProductCode(string productCode)
        {
            var record = conn.Select<CksProductionRecord>()
                .Where(a => a.CreatedTime > DateTime.Now.AddYears(-1) && a.ProductCode == productCode).OrderByDescending(a => a.Id).First();
            if (record == null)
                record = new CksProductionRecord();
            return record;
        }
    }
}
